//
// Created by Administrator on 2025/4/20.
//

#ifndef THREADPOOL_ANY_H
#define THREADPOOL_ANY_H

#include <iostream>
#include <memory>
#include <mutex>

//基类类型，提供这个类去指向所有的派生类对象
class Base{
public:
    virtual ~Base() = default;
private:
};

//派生类
template<typename T>
class Derived : public Base {
public:
    Derived(T data) : _data(data)
    {}
private:
    T _data;
};

class Any {
public:
    Any() = default;
    ~Any() = default;
    //禁用左值拷贝构造和赋值运算符
    Any(const Any&) = delete;
    Any& operator=(const Any&) = delete;
    //启用右值拷贝构造和赋值运算符
    Any(Any&& other) = default;
    Any& operator=(Any&& other) = default;

    //接受一个任意类型的数据
    template<typename T>
    Any(T data) : _base(std::make_unique<Derived<T>>(data))
    {}
    //获取任意类型的数据
    template<typename T>
    T& cast_(){
        Derived<T>* derived = dynamic_cast<Derived<T>*>(_base.get());
        if(derived == nullptr){
//            throw std::bad_cast();
            throw "bad_cast";
        }
        return derived->_data;
    }
private:
    //定义一个基类的指针
    std::unique_ptr<Base> _base;
};


//信号量
class Semaphore {
public:
    Semaphore(int count = 0) : _count(count) {}

    // p操作，增加一个信号量资源
    void post(){
        std::unique_lock<std::mutex> lock(_mtx);
        _count++;
        _cv.notify_all();
    }
    // v操作，减少一个信号量资源
    void wait(){
        std::unique_lock<std::mutex> lock(_mtx);
        _cv.wait(lock, [this]() -> bool {return _count > 0;});
        _count--;
    }
private:
    int _count;// 资源技术
    std::mutex _mtx;
    std::condition_variable _cv;
};



#endif //THREADPOOL_ANY_H
